//
//  COWalletController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/30.
//

import UIKit
import RZColorfulSwift

class COWalletController: COBaseViewController {
    var money: [COMoneyModel] = [] {
        didSet {
            contents = money.map({ item->COWalletCellModel in
                let model = COWalletCellModel()
                model.change(item)
                return model
            })
            
            collectionView.reloadData()
        }
    }
    var contents: [COWalletCellModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(moneyChange), name: NSNotification.Name("CoinChange"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(paySuccess), name: NSNotification.Name(rawValue: "PaySuccess"), object: nil)

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        
        COHomeViewController.getBalance()
        getList()
    }
    override func configUI() {
        self.title = "Wallet"
        view.addSubview(headerView)
        headerView.addSubviews([nameLabel, moneyLabel, moneyImageView])
        view.addSubview(hintLabel)
        view.addSubview(collectionView)
        headerView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight + 71)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(34)
            make.top.equalToSuperview().offset(17)
        }
        
        moneyImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(34)
            make.bottom.equalToSuperview().offset(-33)
        }
        
        moneyLabel.snp.makeConstraints { make in
            make.left.equalTo(moneyImageView.snp.right).offset(3)
            make.bottom.equalTo(moneyImageView.snp.bottom).offset(5)
        }
        
        hintLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(headerView.snp.bottom).offset(30)
        }
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(hintLabel.snp.bottom).offset(0)
        }
    }
    
    private lazy var headerView: UIImageView = {
        let imgV = UIImageView(image: UIImage(named: "金币备份 2"))
        return imgV
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .medium(13)
        label.textColor = .white
        label.text = "Balance (gold coins)"
        return label
    }()
    
    private lazy var moneyImageView: UIImageView = {
        let imgV = UIImageView(image: UIImage(named: "金币"))
        return imgV
    }()
    
    private lazy var moneyLabel: UILabel = {
        let label = UILabel()
        label.font = .medium(30)
        label.textColor = .white
        let num = UserDefaults.standard.integer(forKey: "\(COUserManager.userInfo?.id ?? 0)---coin")
        label.text = "\(num)"
        return label
    }()
    
    private lazy var hintLabel: UILabel = {
        let label = UILabel()
        label.font = .medium(18)
        label.textColor = .white
        label.text = "Select recharge amount"
        return label
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 162, height: 108)
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = SCREENWIDTH - 162*2 - 40
        layout.sectionInset = .init(top: 15, left: 20, bottom: 0, right: 20)
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .rgba(17, 7, 41, 1)
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellWithClass: COWalletCollectionViewCell.self)
        return cv
    }()
}

extension COWalletController: UICollectionViewDelegateFlowLayout {
    
}

extension COWalletController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: COWalletCollectionViewCell.self, for: indexPath)
        cell.model = contents[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = money[indexPath.row]
        let pay = COIPA.shared
        pay.vc = self
        self.view.makeToastActivity(.center)
        pay.start(model.productId)
    }
}

extension COWalletController {
    @objc
    private func moneyChange() {
        let num = UserDefaults.standard.integer(forKey: "\(COUserManager.userInfo?.id ?? 0)---coin")
        moneyLabel.text = "\(num)"
    }
    
    private func getList() {
        self.view.makeToastActivity(.center)
        CONetwork.sendRequest(provider: moneyProvider, target: .list) { text in
            self.view.hideToastActivity()
            guard let array = text.array else {
                return
            }
            self.money = array.map({ dic in
                let model = COMoneyModel.deserialize(from: dic)!
                return model
            })
            
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
    
    @objc
    private func paySuccess() {
        COHomeViewController.getBalance()
        getList()
    }
}
